﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Electure.DAL;
using System.Web.Script.Serialization;

namespace Electure.Admin
{
    public partial class EditPublication : System.Web.UI.Page
    {
        int? Id
        {
            get
            {
                int? res = new int?();
                int id;
                if (int.TryParse(Request.QueryString["id"], out id))
                    res = id;
                return res;
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack) return;

            using (var rep = RepositoryFactory.GetCategoryRepository())
            {
                ddlCategories.Items.Add(new ListItem() { Value = "", Text = "-" });
                rep.GetAll().ForEach(item => ddlCategories.Items.Add(new ListItem() { Value = item.ID.ToString(), Text = item.Name }));
            }

            using (var rep = RepositoryFactory.GetScienceDepartmentRepository())
            {
                ddlScienceDepartments.Items.Add(new ListItem() { Value = "", Text = "-" });
                rep.GetAll().ForEach(item => ddlScienceDepartments.Items.Add(new ListItem() { Value = item.ID.ToString(), Text = item.Name }));
            }
            hfVideoFiles.Value = "{}";
            if (Id.HasValue)
            {
                using (var rep = RepositoryFactory.GetPublicationRepository())
                {
                    var instance = rep.GetById(Id.Value);

                    tbName.Text = instance.Name;
                    tbDescription.Text = instance.Description;

                    if (instance.Image != null)
                        imagePreview.ImageUrl = instance.Image.GetFullPath();

                    if (instance.Category != null)
                        ddlCategories.SelectedValue = instance.Category.ID.ToString();

                    if (instance.ScienceDepartment != null)
                        ddlScienceDepartments.SelectedValue = instance.ScienceDepartment.ID.ToString();


                    var videoFiles = new Dictionary<string, string>();

                    instance.VideoFiles.ForEach(item => { videoFiles.Add(item.ID.ToString(), item.OriginalName); });

                    hfVideoFiles.Value = new JavaScriptSerializer().Serialize(videoFiles);
                }
            }
        }
        protected void button_Command(object sender, CommandEventArgs e)
        {
            if (e.CommandName == "Save")
            {
                int id;
                int? imageId = new int?();
                if (fuImage.HasFile)
                {
                    using (var rep = RepositoryFactory.GetAttachmentRepository())
                    {
                        int _imgId = rep.CreateImageAttachment(Request.PhysicalApplicationPath, fuImage.FileName, fuImage.PostedFile.ContentType, fuImage.FileContent);
                        if (_imgId != -1)
                            imageId = _imgId;
                    }
                }

                var instance = new Publication()
                {
                    Name = tbName.Text,
                    Description = tbDescription.Text
                };

                if (imageId.HasValue)
                    instance.Image = new Attachment() { ID = imageId.Value };

                (new JavaScriptSerializer().Deserialize<Dictionary<string, string>>(hfVideoFiles.Value))
                    .Keys
                    .ToList()
                    .ForEach(item => instance.VideoFiles.Add(new Attachment() { ID = int.Parse(item) }));

                if (!string.IsNullOrEmpty(ddlCategories.SelectedValue))
                    instance.Category = new Category() { ID = int.Parse(ddlCategories.SelectedValue) };
                else
                    instance.Category = null;

                if (!string.IsNullOrEmpty(ddlScienceDepartments.SelectedValue))
                    instance.ScienceDepartment = new ScienceDepartment() { ID = int.Parse(ddlScienceDepartments.SelectedValue) };
                else
                    instance.ScienceDepartment = null;

                using (var rep = RepositoryFactory.GetPublicationRepository())
                {
                    if (Id.HasValue)
                    {
                        instance.ID = Id.Value;
                        if (rep.Update(instance))
                            id = Id.Value;
                        else
                            id = -1;
                    }
                    else
                    {
                        id = rep.Create(instance);
                    }
                }
                if (id != -1)
                    Response.Redirect(string.Format("EditPublication.aspx?id={0}", id));
            }
            else if (e.CommandName == "Cancel")
            {
                Response.Redirect("PublicationList.aspx");
            }
        }
    }
}